<?php


namespace App\Api\Models;

use App\Api\Services\BlackWhite;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Member extends Model
{
    use HasFactory;

    protected $guarded = [];
    protected $table = 'cmc_members';
    protected $hidden = [
        'login_ip', 'last_login_ip', 'last_login_time',  'status',  'password'
    ];

    public function setAvatarAttribute($value)
    {
        $avatar = config('common.avatar');
        return $this->attributes['avatar'] = empty($value) ? $avatar : $value;
    }

    protected function setLoginIpAttr($value)
    {
        return BlackWhite::getClientIp();
    }

    protected function setLastLoginIpAttr($value)
    {
        return BlackWhite::getClientIp();
    }

    protected function setLastLoginTimeAttr($value)
    {
        return date('Y-m-d H:i:s',time());
    }



    /**
     * 登录
     * @param $phone
     * @param $pwd
     * @return bool|\Illuminate\Database\Eloquent\Builder|Model|object|null
     */
    public static function login($phone, $pwd)
    {
        $member = self::query()->where('phone', $phone)->first();
        if ($member) {
            return $pwd = $member->where('password', $pwd)->first();
        }
        return false;
    }

    /**
     * 保存 和更新
     * @param $data
     * @param array $where
     * @return \Illuminate\Database\Eloquent\Builder|Model|int
     */
    public static function saveData($data, $where = [])
    {
        if (!empty($where) && is_array($where)) {
            return self::query()->where($where)->update($data);
        }
        return self::query()->create($data);
    }

    /**
     * 获取密码
     * @param $username
     * @return mixed
     */
    public static function Password($username)
    {
        return self::query()->where('username', $username)->value('password');

    }

    /**
     * 根据id 获取用户详情 (可以指定内容)
     * @param $member_id
     * @param string $filed
     * @return \Illuminate\Database\Eloquent\Builder|Model|object|null
     */
    public static function memberInfo($member_id, $filed='')
    {
        return self::query()->where('member_id', $member_id)->first($filed);
    }

    /**
     * 根据用户id 查询用户
     * @param $id
     * @return mixed
     */
    public static function findMember($id)
    {
        return Member::where('member_id', $id)->count();
    }

    /**
     * 根据指定条件 查询用户ID
     * @param $where
     * @return mixed
     */
    public static function getMemberId($where)
    {
        return self::query()->where($where)->value('member_id');
    }

    /**
     * 根据用户id 获取手机号
     * @param $id
     * @return mixed
     */
    public static function getPhone($id)
    {
        return Member::where('member_id', $id)->value('phone');
    }

    /**
     * 通过手机号获取用户信息
     * @param $where
     * @return mixed
     */
    public static function uniquePhone($phone)
    {
        return self::query()->where('phone', $phone)->first();
    }




}
